package com.qiangzhi.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 阿里云OSS上传文件工具类
 */
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    // 属性会在config包下OssConfiguration注入
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param avatarFile 上传的文件
     * @return 文件上传到阿里云OSS后的路径
     * @throws IOException
     */
    public String upload(MultipartFile avatarFile) throws IOException {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 获取原始文件名
        String originalFilename = avatarFile.getOriginalFilename();
        // 截取原始文件名的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用UUID构建新文件名称
        String objectName = UUID.randomUUID().toString() + extension;

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(avatarFile.getBytes()));
        } catch (OSSException oe) {
            log.error("OSS客户端拒绝响应：{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("连接OSS客户端异常：{}", ce.getMessage());
        } finally {
            if (ossClient != null) ossClient.shutdown();
        }

        // 文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }

}
